// pages/index/index.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";


const QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

qqmapsdk = new QQMapWX({
  key: 'GQCBZ-FUGO5-ZXQII-QU65G-7IRP2-SUFNN'
});


const app = getApp();

var top = app.globalData.navTop;
var isIphoneX = app.globalData.isIphoneX;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 轮播
    isIphoneX: isIphoneX,
    // top:top+70+'px',  //分享
    navTop: top,
    autoplay: true,
    interval: 2000,
    duration: 500,
    // 分享
    fenxiang: false,
    navData: [{
      name: "首页", //文本
      index: 0, //是否是当前页，0不是  1是
      ico: '../images/tabbar/home-sy', //不同图标
      fn: 'gotoIndex', //对应处理函数
      width: 46,
      height: 46,
    }, {
      name: "订单",
      index: 1,
      ico: '../images/tabbar/home-dd',
      fn: 'gotoOrder',
      width: 44,
      height: 44,
    }, {
      name: "自提",
      index: 2,
      ico: '../images/tabbar/home-zt',
      fn: 'gotoSelfhelp',
      width: 44,
      height: 44,
    }, {
      name: "我的",
      index: 3,
      ico: '../images/tabbar/home-wd',
      fn: 'gotoMine',
      width: 40,
      height: 44,
    }, ],
    current: 0,
    currentdd: 1,
    islogin: false,
    address: "加载中···",

    timer: "",
    showaddresstc: false,
    shoplist:"",
    tuangoulist:null,
    num:0,
    zitilist:'',
    showhaibao:false,
    haibaourl:"",
    formatted_addresses:"",
    nogps:''
  },
  getselfhelplist: function () {
    ajax('/api/OrderALLORCode/Get?requestContent=' + JSON.stringify({

      token: wx.getStorageSync("Access_token")
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)
        this.setData({
          zitilist: res.Models
        })

      })
  },

  creathaibao:function(){
    ajax('/api/PosterPictures/Get?requestContent=' + JSON.stringify({

      token: wx.getStorageSync("Access_token")
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)
        this.setData({
          haibaourl: res.Models[0].ImgUrl,
          fenxiang:false,
          showhaibao:true,
        })
       
      })
  },

  tuichuhaibaofx:function(){
    this.setData({
      showhaibao: false,
    })
  },

  postSave(e) {
    wx.showLoading({
      title: '保存中...'
    })
    wx.downloadFile({
      url: this.data.haibaourl,
      success: function (res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '您的推广海报已存入手机相册，赶快分享给好友吧',
              showCancel: false,
            })
          },
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          },
          complete(res) {
            wx.hideLoading()
          }
        })
      }
    })
  },
  // 分享
  // fenxiang:function(){
  //   // console.log('111111111111111111111')
  //   wx.onShareAppMessage(() => {
  //     return {
  //       title: '转发标题',
  //       imageUrl: '' // 图片 URL
  //     }
  //   })
  // },
  // 购物车数量
  getnum:function(){
    ajax('/api/ShopCart/GetShopCartNum?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res,123)
        this.setData({
          num: res.recourdCount
        })
      })
  },

  // 点击查看更多
  seeMore: function (e) {
    var idx = e.currentTarget.dataset.seeid;
    console.log(idx,'idx')

    if (this.data.shoplist[idx].shownum==2){
      var str = "shoplist[" + idx + "].shownum"
      this.setData({
        [str]: 100
      })
    }else{
      var str = "shoplist[" + idx + "].shownum"
      this.setData({
        [str]: 2
      })
    }
  },
  whenchange: function(e) {
    var currentdd = e.detail.current + 1
    this.setData({
      currentdd: currentdd
    })
  },


  toposition: function() {
    wx.navigateTo({
      url: '/pages/opening-address/address?status=' + 1 + '&nogps=' + this.data.nogps,
    })
  },

  toposition11: function () {
    // wx.setStorage("aa","1")
    wx.navigateTo({
      url: '/pages/opening-address/address?status=' +1+'&nogps='+this.data.nogps,
    })
  },

  toposition1: function () {
    wx.navigateTo({
      url: '/pages/opening-address/address?status=' + 2 + '&nogps=' + this.data.nogps,
    })
  },
  
  toshophomepage: function(e) {
    
    wx.navigateTo({
      url: '/pages/shop-homepage/homepage?ID=' + e.currentTarget.dataset.id,
    })
  },

  tosupermarketdetails: function(e) {
    var shopID = e.currentTarget.dataset.shopid
    var ID = e.currentTarget.dataset.id

    wx.navigateTo({
      url: '/pages/supermarket-details/details?shopID=' + shopID + "&ID=" + ID,
    })
  },

  bindGetUserInfo(e) {
    var that = this;
    console.log(e.detail.userInfo,123)
    if (e.detail.userInfo) {
      // 用户按了允许授权按钮
      var code = wx.getStorageSync("code");
      ajax('/api/WXUserLogin/Insert?requestContent=' + JSON.stringify({
        code: code,
        nickname: e.detail.userInfo.nickName,
        avatar: e.detail.userInfo.avatarUrl,
        UserType: 3
      }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)

        wx.setStorageSync("Access_token", res.Access_token)
        this.setData({
          islogin: true
        })

        
        this.getpersondetails()
        this.getindexshop()
        this.gettuangoulist()
        this.getlunbolist()
        this.getnum()
        this.getselfhelplist()

      })
    } else {
      wx.showToast({
        title: '请先授权！',
        icon: 'none',
        duration: 2000
      })

    }
  },



  gotoIndex: function() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  gotoOrder: function() {
    wx.reLaunch({
      url: '/pages/order/order',
    })
  },
  gotoSelfhelp: function() {
    wx.reLaunch({
      url: '/pages/selfhelp/selfhelp',
    })
  },
  gotoMine: function() {
    wx.reLaunch({
      url: '/pages/mine/mine',
    })
  },
  // 分享事件
  shareclick: function() {
    this.setData({
      fenxiang: true
    });
  },
  // 取消分享事件
  quxiao: function() {
    this.setData({
      fenxiang: false
    });
  },
  // 输入框跳转页面
  searchShop: function() {
    wx.navigateTo({
      url: '/pages/coles-search/search',
    })
  },
  // 今日拼购跳转页面
  todayShopping: function() {
    wx.navigateTo({
      url: '/pages/today-shopping/shopping',
    })
  },
  // 897超市
  chaoshi: function() {
    wx.navigateTo({
      url: '/pages/coles/coles',
    })
  },
  // 897团购
  tuangou: function() {
    console.log(1231231)
    wx.navigateTo({
      url: '/pages/group-purchase/purchase',
    })
  },
  // 897团购商品详情
  xiangqing:function(e){
    console.log(e,123456789)
    var ptid = e.currentTarget.dataset.ptid
    wx.navigateTo({
      url: '/pages/group-details/details?PTID=' + ptid,
    })
  },
  // 购物车
  gouwuche: function() {
    wx.navigateTo({
      url: '/pages/gouwuche/gouwuche',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  loadCity: function(longitude, latitude) {
    var that = this;
    // 获取经度纬度
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: (res) => {
        console.log(res)
        console.log("11111111111111")

        if (res.status == 0) {
          var address_component = res.result.address_component;
          var address 
          // var areaName = city.replace(/省|市|自治区|特别行政区|壮族|回族|维吾尔/g, "");
          // 保存在本地
          if (res.result.address_component.province == res.result.address_component.city){
            address = res.result.address_component.city + res.result.address_component.district
          }else{
            address = res.result.address_component.province+ res.result.address_component.city + res.result.address_component.district
          }
         

          that.setaddress(address)

          wx.setStorageSync('address_component', address_component);
          wx.setStorageSync('address', address);

          wx: wx.setStorageSync('currentaddress', address_component.district)

          wx.setStorageSync('formatted_addresses', res.result.formatted_addresses.recommend);

          wx.setStorageSync('formatted_addressescopy', res.result.formatted_addresses.recommend);

          this.setData({
            formatted_addresses: res.result.formatted_addresses.recommend
          })

          this.panduaniskaitong()
        }
      }
    })
  },

  setaddress: function (address){
    this.setData({
      address:address
    })
    
  },

  panduaniskaitong:function(){
    ajax('/api/RegionShop/Get?requestContent=' + JSON.stringify({
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district

      // ProvinceName: "",
      // CityName: "",
      // DistrictName: ""
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {

        console.log(res)
        if (res.Models != null){

          console.log(res.Models.ProvinceName)

          console.log(wx.getStorageSync('address_component').province)

          if (res.Models[0].ProvinceName == wx.getStorageSync('address_component').province) {
            this.setData({
              ykt: 1
            })
            console.log("sssssssssssssssssss")
            this.getpersondetails()
            this.getindexshop()
            this.gettuangoulist()
            this.getlunbolist()
            console.log("sssssssssssssssssss")
            this.getnum()
            this.getselfhelplist()
            console.log("sssssssssssssssssss")
          }
        }
         else if (res.Models==null){
          wx.navigateTo({
            url: '/pages/opening-address/address?status=' + 0,
          })
        }

      })

  },

  //  获取经度纬度
  getaddress: function() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy

        wx.setStorageSync("latitude", latitude )
        wx.setStorageSync("longitude", longitude )
        this.loadCity(longitude, latitude)
        // console.log("sssss")
      },
      fail: (res) => {

        console.log(res)

    

        if (res.errCode == 2){
          wx.showToast({
            title: '手机未开启gps',
            icon: 'none',
            duration: 2000
          })

          // wx.setStorageSync("nogps", "1")

          // wx.setStorageSync("PersonID", "ssssssssssssssssssssssssss")
          this.setData({
            nogps:1
          })

          this.toposition11()

          // console.log("weisha")
        }else{
          this.setData({
            showaddresstc: true
          })
        }
        
       
      }
    })
  },


  getindexshop: function() {
    ajax('/api/Homesearch/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopName: "",
      Province: wx.getStorageSync('address_component').province,
      City: wx.getStorageSync('address_component').city,
      District: wx.getStorageSync('address_component').district,
      lng: wx.getStorageSync('longitude'),
      lat: wx.getStorageSync('latitude')
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "get",
    }, res => {
      // console.log(res)
      var shoplist = res.Models
      for (var x in shoplist ){
        shoplist[x].shownum=2

        if (shoplist[x].distance!=0.000){
          if (shoplist[x].distance>1){
            shoplist[x].distance = Number(shoplist[x].distance).toFixed(1)
          }else{
            shoplist[x].distance = Number(shoplist[x].distance).toFixed(3)
          }
        }
      }

      this.setData({
        shoplist: shoplist
      })
      // console.log(this.data.shoplist,'this.data.shoplist')

    })

  },

  getpersondetails: function () {
    ajax('/api/PersonDetails/GetInfo?requestContent=' + JSON.stringify({
      token: wx.getStorageSync("Access_token")
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        // console.log(res)
        if (res.Models!=null){
          wx.setStorageSync("PersonID", res.Models[0].UserID)
        }
      })
  },

  gettuangoulist:function(){
    ajax('/api/Groupbuying/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      PageIndex:0,
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)
        var tuangoulist = res.Models
      
        this.setData({
          tuangoulist: tuangoulist
        })
        // console.log(this.data.shoplist,'this.data.shoplist')

      })

  },
  getlunbolist: function () {
    ajax('/api/SlideShowPerson/get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      Province: wx.getStorageSync('address_component').province,
      City: wx.getStorageSync('address_component').city,
      District: wx.getStorageSync('address_component').district
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)
        
        // console.log(this.data.shoplist,'this.data.shoplist')
        this.setData({
          lunbolist: res.Models
        })
      })

  },

  onLoad: function(options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    var address_component=wx.getStorageSync('address_component')

    var address = wx.getStorageSync('address')

    var formatted_addresses = wx.getStorageSync('formatted_addresses')

    if (address_component){
      this.setData({
        address: address,
        formatted_addresses: formatted_addresses
      })
    }else{
      this.getaddress()
    }

    var token = wx.getStorageSync("Access_token")
    if (token) {
      this.setData({
        islogin: true
      })
      // this.getpersondetails()
      // this.getindexshop()
      // this.gettuangoulist()
      // this.getlunbolist()
      // this.getnum()

      // this.getselfhelplist()
    }else{
      
    }
    this.getpersondetails()
    this.getindexshop()
    this.gettuangoulist()
    this.getlunbolist()
    this.getnum()

    this.getselfhelplist()

    this.setData({
      showaddresstc: false
    })
   

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */


  sleep(delay) {
    var start = (new Date()).getTime();
    while ((new Date()).getTime() - start < delay) {
      continue;
    }
  },

  onPullDownRefresh: function() {
    wx.showNavigationBarLoading();
    var that = this;

    this.sleep(1000)
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {

      title: '897便利购', //转发的标题

      path: `pages/index/index`,//转发的连接 后面带 id

      imageUrl: ''
    } //转发的图片
  }
})